<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
             label-width="120px">
      <el-upload v-model:file-list="fileList"
                 class="upload-demo"
                 :action="dataForm.upload"
                 multiple
                 :on-preview="handlePreview"
                 :on-remove="handleRemove"
                 :before-remove="beforeRemove"
                 :before-upload="beforeUpload"
                 :on-success="handleSuccess"
                 :limit="5"
                 :on-exceed="handleExceed">
        <el-button type="primary">上传报告</el-button>
        <template #tip>
          <div class="el-upload__tip">
            <!--            jpg/png files with a size less than 500KB.-->
          </div>
        </template>
      </el-upload>
    </el-form>

    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, ref} from "vue";
import baseService from "@/service/baseService";
import type {UploadProps, UploadUserFile} from "element-plus";
import {ElMessage, ElMessageBox} from "element-plus";
import {getToken} from "@/utils/cache";

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();

const fileList = ref<UploadUserFile[]>([]);

const dataForm = reactive({
  id: "",
  reports: "",
  upload: "",
  fileLimit: false
});

const rules = ref({
  // bkId: [{required: true, message: '必填项不能为空', trigger: 'blur'}],
  // bkName: [{required: true, message: '必填项不能为空', trigger: 'blur'}]
});

const init = (id?: number) => {
  visible.value = true;
  fileList.value = [];
  dataForm.id = "";
  dataForm.upload = `${window.SITE_CONFIG['apiURLUpload']}?token=${getToken()}&type=reports`

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  //获取项目列表
  // Promise.all([getUserList("")]).then(() => {
  if (id) {
    getInfo(id);
  }
  // });
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/yckj/order/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    fileList.value = JSON.parse(dataForm.reports == null ? "[]" : dataForm.reports);
  });
};

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  // console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(`最多可传5个文件, 你已传 ${files.length} 文件,请修改`);
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  if (!dataForm.fileLimit) {
    return ElMessageBox.confirm(`是否删除 [${uploadFile.name}] ?`).then(
      () => true,
      () => false
    );
  } else {
    return true;
  }
};

const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  const isLt30M = file.size / 1024 / 1024 < 3; // 文件大小限制为2MB
  if (!isLt30M) {
    ElMessage.warning(`上传文件大小不能超过 30MB!`);
    dataForm.fileLimit = true;
    return false; // 返回false则阻止文件上传
  } else {
    dataForm.fileLimit = false;
    return true; // 返回true则允许文件上传
  }
};
const handleSuccess: UploadProps["onSuccess"] = (response, file, fileList) => {
  // console.log("success1", response); // 处理上传成功的逻辑
  // console.log("success2", file); // 处理上传成功的逻辑
  // console.log("success3", fileList); // 处理上传成功的逻辑
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    dataForm.reports = JSON.stringify(fileList.value);
    (!dataForm.id ? baseService.post : baseService.put)("/yckj/order/updateReports", dataForm).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
